<template>
  <section class="inner-bottom">
    <section class="content clear">
      <section class="content-search">
        <div class="fl">
          <el-input size="mini" v-model="sear.keyword" placeholder="请输入操作人姓名/学工号"></el-input>
        </div>
        <div class="fl ml20">
          <el-select size="mini" v-model="sear.type" placeholder="请选择岗位">
            <el-option :key="index" v-for="(item,index) in extendRoleList" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </div>
        <div class="fl ml20">
          <el-button size="mini" type="primary" @click="search">搜索</el-button>
        </div>
        <div class="fr ml20">
          <el-button size="mini" type="primary" @click="showBatchAuthorizeTeacherDialog">批量授权教师</el-button>
        </div>
        <div class="fr ml20">
          <el-button size="mini" type="primary" @click="authorizeTearch">授权教师</el-button>
        </div>
        <div class="fr">
          <el-button size="mini" type="primary" @click="showAuthorizeStudentDialog">授权学生</el-button>
        </div>
      </section>
      <section class="content-list">
        <el-table :data="managePersonList" stripe style="width: 100%">
          <el-table-column prop="date" label="序号" width="120">
            <template slot-scope="scope"><span>{{scope.$index+(currentPage - 1) * pageSize + 1}} </span></template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="180"></el-table-column>
          <el-table-column prop="sn" label="工号/学号" width="180"></el-table-column>
          <el-table-column prop="address" label="岗位名称">
            <template slot-scope="scope"><span>{{scope.row | formatRole}} </span></template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="checkList(scope.row.id)">查看</el-button>
              <el-button type="text" size="mini" @click="updateManagePerson(scope.row)">修改</el-button>
              <el-button @click="showRoleManageDialog(scope.row)" type="text" size="mini">岗位管理</el-button>
              <el-button @click="deleteManagePerson(scope.row.id)" class="text-error" type="text" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </section>
      <section class="content-page">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 15, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
        </el-pagination>
      </section>
    </section>
    <el-dialog title="岗位管理" :visible.sync="dialogRoleManage">
      <section class="clear">
        <el-form>
          <el-form-item label="姓名：" class="fl" style="width: 230px">
            <span>{{currentOperateItem.name}}</span>
          </el-form-item>
          <el-form-item label="工号/学号：" class="fl" style="width: 230px">
            <span>{{currentOperateItem.sn}}</span>
          </el-form-item>
        </el-form>
      </section>
      <div style="text-align: center">
        <el-transfer style="text-align: left; display: inline-block" :props="{
      key: 'id',
      label: 'name'
    }" v-model="userRoles" :titles="['未授权岗位', '授权岗位']" :button-texts="['加到左侧', '加到右侧']" :data="allRoles">
        </el-transfer>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleManage = false">取 消</el-button>
        <el-button type="primary" @click="updateUserRole()">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="批量授权教师" :visible.sync="dialogBatchAuthorizeTeacher" width="30%" @closed="clearBatchAuthorizeTeacher('batchFileUploadForm')">
      <section class="content-search">
        <el-form ref="batchFileUploadForm" :rules="batchFileUploadRules" :model="batchFileUploadForm">
          <el-form-item label="上传：">
            <el-upload class="file-uploader" ref="upload" :data="extraUploadData" :action="prodUrl('./api/manager/batchGrantTeacher')" :file-list="fileList" :auto-upload="false" :on-success="handleUploadSuccess" :on-change="onFileChange">
              <el-button slot="trigger" size="small"><i class="el-icon-upload2"></i> 上传文件</el-button> <a target="_blank" :href="downloadTemplateUrl" class="download-template">下载模板</a>
              <div slot="tip" class="el-upload__tip">支持上传文件格式：xls/xlsx，单个文档不大于8M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="岗位：" prop="selectRoles">
            <el-select v-model="batchFileUploadForm.selectRoles" size="small" multiple placeholder="请选择">
              <el-option v-for="(item,index) in roleList" :key="index" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchAuthorizeTeacher = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload('batchFileUploadForm')">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加学生管理者" :visible.sync="dialogAuthorizeStudent" @open="getAddRoleColleges" @close="clearStudentInfo">
      <section class="content-search">
        <el-form>
          <section class="clear">
            <el-form-item label="学生管理者：" class="fl" style="width:400px">
              <el-autocomplete v-if="isCreateOrUpdateStudent==='create'" :clearable="true" :trigger-on-focus="false" size="small" popper-class="my-autocomplete" v-model="studentManage" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.name }}</div>
                </template>
              </el-autocomplete>
              <i class="el-icon-success" v-if="isCreateOrUpdateStudent==='create'&&studentInfo.id" style="color:#67C23A;"></i>
              <el-input v-if="isCreateOrUpdateStudent==='update'" style="width:200px" size="mini" v-model="studentInfo.name" disabled="true" placeholder="请输入操作人姓名/学工号"></el-input>
            </el-form-item>
            <el-form-item label="选择岗位：" class="fl ml20" style="width:400px">
              <el-select size="mini" placeholder="请选择岗位" v-model="selectRoleId">
                <el-option :key="index" v-for="(item,index) in  studentInfo.managerRoles" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </section>
          <section class="clear">
            <div class="fl">
              学院 <el-select size="mini" v-model="addRuleSelectCollege" placeholder="请选择学院" style="width:120px" @change="getAddRoleMajorsAndGradeByCollege">
                <el-option :key="index" v-for="(item,index) in  addRuleColleges" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
            <div class="fl ml20">
              专业 <el-select size="mini" v-model="addRuleSelectMajor" placeholder="请选择专业" style="width:120px" @change="getAddRoleGradesByMajor">
                <el-option :key="index" v-for="(item,index) in  addRuleMajors" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
            <div class="fl ml20">
              年级 <el-select size="mini" v-model="addRuleSelectGrade" placeholder="请选择年级" style="width:120px" @change="getAddRoleClassesByMajorAndGrade">
                <el-option :key="index" v-for="(item,index) in  addRuleGrades" :label="item" :value="item"></el-option>
              </el-select>
            </div>
            <div class="fl ml20">
              班级 <el-select size="mini" v-model="addRuleSelectClazz" placeholder="请选择班级" style="width:120px" @change="getAddRoleStudentsByClass">
                <el-option :key="index" v-for="(item,index) in  addRuleClazzs" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
            <!-- <div class="fl ml20">
              学生 <el-select size="mini" v-model="addRuleSelectStudent" placeholder="请选择学生" style="width:120px">
                <el-option :key="index" v-for="(item,index) in  addRuleStudents" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div> -->
          </section>
          <section class="clear">
            <div style="margin: 15px auto;">备注：新增管辖范围可以按集体新增（如整个学院，专业等）</div>
            <el-button size="small" type="primary" @click="addRuleItem">添加</el-button>
            <div placeholder="最多添加10个管辖范围" style="    min-height: 150px;
    border: 1px solid #c5c2c2;
    border-radius: 8px;
    margin: 10px auto;
    padding: 5px;">
              <span class="message" v-if="roleItems.length===0">最多添加10个管辖范围</span>
              <div :key="index" v-for="(item,index) in roleItems">{{(index+1)+ '、'}}{{ item | rulefilter}}</div>
            </div>
          </section>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAuthorizeStudent = false">取 消</el-button>
        <el-button type="primary" @click="submitRule">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="授权老师" :visible.sync="dialogAuthorizeTeacher" width="1000px" @closed="clearAuthorizeTeacher('teacherForm')">
      <el-form :model="teacherForm" :rules="teacherRules" ref="teacherForm" label-width="120px">
        <section class="clear ">
          <section class="fl" style="width:60%;box-sizing:border-box;padding-right:100px;">
            <div style="color: #333;font-size: 16px;margin-bottom: 10px;">基础信息</div>
            <section class="fl" style="width:100%;padding-right:30px;border-right:1px solid #80808066;">
              <section class="clear">
                <section class="fl">
                  <el-form-item label="职工号：" prop="sn" class="w330">
                    <el-input size="mini" v-model="teacherForm.sn" autocomplete="off" :disabled="isCreateOrUpdateTeacher==='update'" placeholder="请输入职工号"></el-input>
                  </el-form-item>
                  <el-form-item label="姓名：" prop="name" class="w330">
                    <el-input size="mini" style="width:100px" v-model="teacherForm.name" autocomplete="off" :disabled="isCreateOrUpdateTeacher==='update'" placeholder="请输入姓名"></el-input>
                    <el-radio-group class="ml10" v-model="teacherForm.gender" placeholder="请选择性别">
                      <el-radio v-for="item in genderOption" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="民族：" prop="nationId" class="w330">
                    <el-select size="mini" v-model="teacherForm.nationId" placeholder="请选择民族">
                      <el-option :key="index" v-for="(item,index) in nations" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </section>
                <section class="fr">
                  <el-upload class="avatar-uploader" :action="prodUrl('./api/common/uploadFile')" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="teacherForm.picUrl" :src="`./api/common/getHeadPic?picUrl=${teacherForm.picUrl}`" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </section>
              </section>
              <el-form-item label="政治面貌：" prop="politicalStatus">
                <el-select size="mini" v-model="teacherForm.politicalStatus" placeholder="请选择政治面貌">
                  <el-option :key="index" v-for="(item,index) in politicStatus" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="籍贯：" prop="nativePlaceId">
                <el-select size="mini" v-model="teacherForm.nativePlaceId" placeholder="请选择籍贯">
                  <el-option :key="index" v-for="(item,index) in provinces" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身份证类型：" prop="idType">
                <el-select size="small" style="width:100px" v-model="teacherForm.idType" placeholder="请选择身份证类型">
                  <el-option :key="index" v-for="(item,index) in idTypes" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
                <el-form-item prop="idNumber" class="fr">
                  <el-input size="mini" style="width:220px" v-model="teacherForm.idNumber" autocomplete="off" placeholder="请输入身份证号码"></el-input>
                </el-form-item>
              </el-form-item>
              <el-form-item label="校区：" prop="campusId">
                <el-select size="small" v-model="teacherForm.campusId" placeholder="请选择校区">
                  <el-option :key="index" v-for="(item,index) in campus" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="岗位：" prop="roleIds" v-if="isCreateOrUpdateTeacher==='create'">
                <el-select size="small" v-model="teacherForm.roleIds" multiple placeholder="请选择岗位">
                  <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </section>
          </section>
          <section class="fr" style="width:40%">
            <div style="color: #333;font-size: 16px;margin-bottom: 10px;">本人联系信息</div>
            <section>
              <el-form-item label="本人电话：" prop="phone" class="w330">
                <el-input size="mini" v-model="teacherForm.phone" autocomplete="off" placeholder="请输入本人电话"></el-input>
              </el-form-item>
              <el-form-item label="邮箱：" prop="email" class="w330">
                <el-input size="mini" v-model="teacherForm.email" autocomplete="off" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item label="微信号：" prop="wechat" class="w330">
                <el-input size="mini" v-model="teacherForm.wechat" autocomplete="off" placeholder="请输入微信号"></el-input>
              </el-form-item>
              <el-form-item label="QQ：" prop="qq" class="w330">
                <el-input size="mini" v-model="teacherForm.qq" autocomplete="off" placeholder="请输入QQ"></el-input>
              </el-form-item>
              <div style="float: right;margin: 50px;">
                <span>注意：标有 * 的必须填写,请尽量填写真 </span><br />
                <span>实资料,不会对您产生任何不良影响，我 </span><br />
                <span>们将为你严格保密。</span>
              </div>
            </section>
          </section>
        </section>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogAuthorizeTeacher = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addTeacherRuleArea('teacherForm')">{{isCreateOrUpdateTeacher==='create'?'添加管辖范围':'下一步'}}</el-button>
        <el-button size="mini" type="primary" @click="submitTeacherInfo('teacherForm')">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加管辖范围" :visible.sync="dialogTeacherRuleArea" @open="getAddRoleColleges" @close="clearTeacherInfo">
      <section class="content-search">
        <el-form>
          <section class="clear">
            <el-form-item label="教师名称：" class="fl" style="width:340px">
              {{teacherInfo.name}}
            </el-form-item>
            <el-form-item label="教师岗位：" class="fl ml20" style="width:340px">
              <el-select size="mini" placeholder="请选择岗位" v-model="selectRoleId">
                <el-option :key="index" v-for="(item,index) in  teacherInfo.managerRoles" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </section>
          <section class="clear">
            <div class="fl">
              学院 <el-select size="mini" v-model="addRuleSelectCollege" placeholder="请选择学院" style="width:120px" @change="getAddRoleMajorsAndGradeByCollege">
                <el-option :key="index" v-for="(item,index) in  addRuleColleges" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
            <div class="fl ml20">
              专业 <el-select size="mini" v-model="addRuleSelectMajor" placeholder="请选择专业" style="width:120px" @change="getAddRoleGradesByMajor">
                <el-option :key="index" v-for="(item,index) in  addRuleMajors" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
            <div class="fl ml20">
              年级 <el-select size="mini" v-model="addRuleSelectGrade" placeholder="请选择年级" style="width:120px" @change="getAddRoleClassesByMajorAndGrade">
                <el-option :key="index" v-for="(item,index) in  addRuleGrades" :label="item" :value="item"></el-option>
              </el-select>
            </div>
            <div class="fl ml20">
              班级 <el-select size="mini" v-model="addRuleSelectClazz" placeholder="请选择班级" style="width:120px" @change="getAddRoleStudentsByClass">
                <el-option :key="index" v-for="(item,index) in  addRuleClazzs" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
            <!-- <div class="fl ml20">
              学生 <el-select size="mini" v-model="addRuleSelectStudent" placeholder="请选择学生" style="width:120px">
                <el-option :key="index" v-for="(item,index) in  addRuleStudents" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div> -->
          </section>
          <section class="clear">
            <div style="margin: 15px auto;">备注：新增管辖范围可以按集体新增（如整个学院，专业等）</div>
            <el-button size="small" type="primary" @click="addRuleItem">添加</el-button>
            <div placeholder="最多添加10个管辖范围" style="    min-height: 150px;
    border: 1px solid #c5c2c2;
    border-radius: 8px;
    margin: 10px auto;
    padding: 5px;">
              <span class="message" v-if="roleItems.length===0">最多添加10个管辖范围</span>
              <div :key="index" v-for="(item,index) in roleItems">{{(index+1)+ '、'}}{{ item | rulefilter}}</div>
            </div>
          </section>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTeacherRuleArea = false">取 消</el-button>
        <el-button type="primary" @click="submitTeacherRuleArea">保 存</el-button>
      </span>
    </el-dialog>
    <!--新增老师失败对话框-->
    <el-dialog title="批量新增" :visible.sync="dialogBatchAddError" width="30%">
      <section class="content-search">
        <div style="text-align:center">
          <i class="el-icon-error" style="color: red;
    font-size: 20px;
    vertical-align: middle;
    margin-right: 10px;"></i>上传失败！
        </div>
        <div style="margin: 15px 0;color: #3a8ee6cc;">
          重复人数：{{duplicateSns.length}}
        </div>
        <div>
          <div :key="index" v-for="(item,index) in duplicateSns" style="width:33%;display:inline-block">{{item}}</div>
        </div>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchAddError = false">取 消</el-button>
        <el-button type="primary" @click="dialogBatchAddError = false">保 存</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import { people } from '@/api/index'
import { _checkSn, _checkMobilePhone, _checkQQ, _checkIdNum, prodUrl } from '@/tools/utils'
export default {
  name: 'management',
  data () {
    return {
      nations: [],
      politicStatus: [],
      provinces: [],
      campus: [],
      idTypes: [
        {
          id: 1,
          name: '身份证'
        }, {
          id: 2,
          name: '护照'
        }
      ],

      roleList: [],
      selectRoles: [],
      extendRoleList: [],
      managePersonList: [],
      allRoles: [],
      userRoles: [],
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      sear: {
        type: null,
        keyword: ''
      },
      dialogRoleManage: false,
      dialogAuthorizeTeacher: false,
      currentOperateItem: {},
      dialogBatchAuthorizeTeacher: false,
      dialogAuthorizeStudent: false,
      // 批量授权教师上传模块相关数据
      batchFileUploadForm: {
        selectRoles: []
      },
      batchFileUploadRules: {
        selectRoles: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },

      fileList: [],
      duplicateSns: [],
      dialogBatchAddError: false,
      // uploadUrl: './api/manager/batchGrantTeacher',
      downloadTemplateUrl: './templates/批量授权教师模板.xlsx',

      studentManage: '',
      studentInfo: {},
      selectRoleId: undefined,

      addRuleColleges: [],
      addRuleMajors: [],
      addRuleGrades: [],
      addRuleClazzs: [],
      addRuleStudents: [],

      addRuleSelectCollege: undefined,
      addRuleSelectMajor: undefined,
      addRuleSelectGrade: undefined,
      addRuleSelectClazz: undefined,
      addRuleSelectStudent: undefined,

      roleItems: [],
      teacherInfo: {},
      dialogTeacherRuleArea: false,
      isCreateOrUpdateTeacher: 'create',
      isCreateOrUpdateStudent: 'create',
      teacherForm: {
        roleIds: [],
        id: undefined,
        picUrl: '',
        sn: '',
        name: '',
        gender: 1,
        nationId: undefined,
        politicalStatus: undefined,
        nativePlaceId: undefined,
        idType: undefined,
        idNumber: '',
        phone: '',
        qq: '',
        wechat: '',
        email: '',
        campusId: undefined
      },
      teacherRules: {
        sn: [
          { required: true, message: '请输入职工号', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' },
          { validator: _checkSn, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ],
        idNumber: [
          { validator: _checkIdNum, trigger: 'blur' }
        ],
        phone: [
          { validator: _checkMobilePhone, trigger: 'blur' }
        ],
        qq: [
          { validator: _checkQQ, trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
          { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' }
        ],
        wechat: [
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ]
      },
      genderOption: [{
        label: '男',
        value: 1
      }, {
        label: '女',
        value: 2
      }]

    }
  },
  computed: {
    // 批量上传额外带的角色数组数据
    extraUploadData: function () {
      return {
        role: this.batchFileUploadForm.selectRoles
      }
    }
  },
  created: function () {
    this.getRoleList()
    this.getAllRoleList()
    this.getManagePersonList()
    this.getNations()
    this.getPoliticStatus()
    this.getProvinces()
    this.getCampus()
  },
  methods: {
    prodUrl,
    getNations () {
      return people()._getNations().then((res) => {
        if (res.status) {
          this.nations = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getPoliticStatus () {
      return people()._getPoliticStatus().then((res) => {
        if (res.status) {
          this.politicStatus = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getProvinces () {
      return people()._getProvinces().then((res) => {
        if (res.status) {
          this.provinces = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getCampus () {
      return people()._getCampus().then((res) => {
        if (res.status) {
          this.campus = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getRoleList () {
      people()._getManagerRoles().then((res) => {
        if (res.status) {
          this.roleList = [...res.data]
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getAllRoleList () {
      return people()._getRoleList().then((res) => {
        if (res.status) {
          this.extendRoleList = [...res.data]
          this.extendRoleList.push({
            id: null,
            name: '不限岗位'
          })
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getGradesByCollege (collegeId) {
      return people()._getGradesByCollege(collegeId).then((res) => {
        if (res.status) {
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getManagePersonList () {
      people()._getManagePersonList({
        roleId: this.sear.type,
        filterValue: this.sear.keyword,
        orderByColumn: '',
        orderByType: '',
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }).then((res) => {
        if (res.status) {
          this.managePersonList = res.data.pageData
          this.totalCount = res.data.totalCount
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    search () {
      this.getManagePersonList()
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getManagePersonList()
    },
    handleCurrentChange (currentPage) {
      this.currentPage = currentPage
      this.getManagePersonList()
    },
    checkList (val) {
      this.$emit('check', val)
    },

    showRoleManageDialog (item) {
      this.dialogRoleManage = true
      this.currentOperateItem = item
      people()._getManagerRoles().then((res) => {
        if (res.status) {
          this.allRoles = res.data.map((item) => {
            item.id === 1 ? item.disabled = true : item.disabled = false
            return item
          })
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
      people()._getUserRoles(this.currentOperateItem.id).then((res) => {
        if (res.status) {
          this.userRoles = res.data.map((item) => {
            return item.id
          })
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    deleteManagePerson (id) {
      this.$confirm('此操作将永久删除管理人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        people()._deleteStudent(id).then((res) => {
          if (res.status) {
            this.$message.success('删除管理人员成功')
            this.getManagePersonList()
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    updateUserRole () {
      people()._updateUserRole({
        userId: this.currentOperateItem.id,
        roleIds: this.userRoles
      }).then((res) => {
        if (res.status) {
          this.$message.success('授权成功')
          this.dialogRoleManage = false
          this.getManagePersonList()
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    showBatchAuthorizeTeacherDialog () {
      this.dialogBatchAuthorizeTeacher = !this.dialogBatchAuthorizeTeacher
    },
    showAuthorizeStudentDialog () {
      this.dialogAuthorizeStudent = !this.dialogAuthorizeStudent
      this.isCreateOrUpdateStudent = 'create'
      people()._getManagerRoles().then((res) => {
        if (res.status) {
          this.studentInfo.managerRoles = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    onFileChange (file) {
      this.fileList = []

      let isLt8M = file.size / 1024 / 1024 < 8

      let suffix = file.name.split('.')[1]

      if (suffix !== 'xls' && suffix !== 'xlsx') {
        this.$message.error('上传文件只能是 xls|xlsx 格式!')
        return false
      }
      if (!isLt8M) {
        this.$message.error('上传文件大小不能超过 8MB!')
        return false
      }

      this.fileList = [file]
    },
    submitUpload (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.warning('请选择要上传的文件!')
            return false
          }
          this.$refs.upload.submit()
        } else {
          return false
        }
      })
    },
    handleUploadSuccess (res, file, fileList) {
      if (res.status) {
        this.$message.success('批量上传成功')
        this.dialogBatchAuthorizeTeacher = false
        this.getManagePersonList()
      } else if (!res.status && res.data && res.data.length > 0) {
        this.duplicateSns = res.data
        this.dialogBatchAddError = true
        setTimeout(() => {
          this.fileList = []
        })
      } else {
        this.$message.error(res.message)
        setTimeout(() => {
          this.fileList = []
        })
      }
    },
    clearBatchAuthorizeTeacher (formName) {
      this.$refs[formName].resetFields()
      this.fileList = []
    },
    querySearch (queryString, cb) {
      people()._findBySnAndOnlyStudentRole(queryString).then((res) => {
        if (res.status) {
          let results = []
          if (res.data) {
            results = [res.data]
            cb(results)
          } else {
            results = []
            cb(results)
          }
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    handleSelect (item) {
      this.studentInfo.id = item.id
      this.studentInfo.name = item.name

      this.studentManage = item.sn + ' ' + item.name
    },
    getCollegeData () {
      return people()._getColleges().then((res) => {
        if (res.status) {
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getMajorDataByCollege (collegeId) {
      return people()._getMajorsByCollege(collegeId).then((res) => {
        if (res.status) {
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getGradeDataByMajor (majorId) {
      return people()._getGradesByMajor(majorId).then((res) => {
        if (res.status) {
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getClassDataByMajorAndGrade (majorId, grade) {
      return people()._getClassesByMajorAndGrade(majorId, grade).then((res) => {
        if (res.status) {
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getStudentDataByClass (clazzId) {
      return people()._findByClassId({
        clazzId: clazzId,
        filterValue: '',
        orderByColumn: '',
        orderByType: '',
        pageNum: 1,
        pageSize: 1000
      }).then((res) => {
        if (res.status) {
          return res
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getAddRoleColleges () {
      this.addRuleSelectMajor = undefined
      this.addRuleSelectGrade = undefined
      this.addRuleSelectClazz = undefined
      this.addRuleSelectStudent = undefined
      this.addRuleSelectCollege = undefined
      this.getCollegeData().then((res) => {
        this.addRuleColleges = res.data
      })
    },
    getAddRoleMajorsAndGradeByCollege (collegeId) {
      this.addRuleSelectMajor = undefined
      this.addRuleSelectGrade = undefined
      this.addRuleSelectClazz = undefined
      this.addRuleSelectStudent = undefined
      this.getMajorDataByCollege(collegeId).then((res) => {
        this.addRuleMajors = res.data
      })
      this.getGradesByCollege(collegeId).then((res) => {
        this.addRuleGrades = res.data
      })
    },
    getAddRoleGradesByMajor (majorId) {
      this.addRuleSelectGrade = undefined
      this.addRuleSelectClazz = undefined
      this.addRuleSelectStudent = undefined
      this.getGradeDataByMajor(majorId).then((res) => {
        this.addRuleGrades = res.data
      })
    },
    getAddRoleClassesByMajorAndGrade (grade) {
      this.addRuleSelectClazz = undefined
      this.addRuleSelectStudent = undefined
      if (this.addRuleSelectMajor) {
        this.getClassDataByMajorAndGrade(this.addRuleSelectMajor, grade).then((res) => {
          this.addRuleClazzs = res.data
        })
      }
    },
    getAddRoleStudentsByClass (clazzId) {
      this.addRuleStudents = undefined
      this.getStudentDataByClass(clazzId).then((res) => {
        this.addRuleStudents = res.data.pageData
      })
    },
    addRuleItem () {
      if (this.roleItems.length >= 10) {
        this.$message.warning('最多添加10条管辖范围')
        return
      }
      if (!this.addRuleSelectCollege) {
        this.$message.warning('请选择管辖范围！')
        return
      }
      let currentSelectObj = {
        clazz: this.addRuleSelectClazz !== undefined ? this.addRuleClazzs.find((item) => { return item.id === this.addRuleSelectClazz }).name : null,
        clazzId: this.addRuleSelectClazz !== undefined ? this.addRuleSelectClazz : null,
        college: this.addRuleSelectCollege !== undefined ? this.addRuleColleges.find((item) => { return item.id === this.addRuleSelectCollege }).name : null,
        collegeId: this.addRuleSelectCollege !== undefined ? this.addRuleSelectCollege : null,
        grade: this.addRuleSelectGrade !== undefined ? this.addRuleSelectGrade : null,
        major: this.addRuleSelectMajor !== undefined ? this.addRuleMajors.find((item) => { return item.id === this.addRuleSelectMajor }).name : null,
        majorId: this.addRuleSelectMajor !== undefined ? this.addRuleSelectMajor : null,
        name: this.addRuleSelectStudent !== undefined ? this.addRuleStudents.find((item) => { return item.id === this.addRuleSelectStudent }).name : null,
        sn: this.addRuleSelectStudent !== undefined ? this.addRuleStudents.find((item) => { return item.id === this.addRuleSelectStudent }).sn : null,
        studentId: this.addRuleSelectStudent !== undefined ? this.addRuleSelectStudent : null
      }
      let isHasRepeat = this.roleItems.filter(item => {
        return JSON.stringify(item) === JSON.stringify(currentSelectObj)
      })
      if (isHasRepeat.length !== 0) {
        this.$message.warning('请勿重复添加！')
        return
      }
      this.roleItems.push(currentSelectObj)
    },
    submitRule () {
      if (this.isCreateOrUpdateStudent === 'create') {
        if (!this.studentInfo.id) {
          this.$message.info('请选择学生管理者')
          return false
        }
        people()._giveStudentPower({
          managerId: this.studentInfo.id,
          roleId: this.selectRoleId,
          scopeDetails: this.roleItems
        }).then((res) => {
          if (res.status) {
            this.$message.success('新增学生管理者成功')
            this.dialogAuthorizeStudent = false
            this.getManagePersonList()
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error(err)
        })
      } else if (this.isCreateOrUpdateStudent === 'update') {
        people()._giveStudentPower({
          managerId: this.studentInfo.id,
          roleId: this.selectRoleId,
          scopeDetails: this.roleItems
        }).then((res) => {
          if (res.status) {
            this.$message.success('修改学生管理范围成功')
            this.dialogAuthorizeStudent = false
            this.getManagePersonList()
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error(err)
        })
      }
    },
    authorizeTearch () {
      this.dialogAuthorizeTeacher = true
      this.isCreateOrUpdateTeacher = 'create'
      this.teacherForm = {
        roleIds: [],
        id: undefined,
        picUrl: '',
        sn: '',
        name: '',
        gender: 1,
        nationId: undefined,
        politicalStatus: undefined,
        nativePlaceId: undefined,
        idType: undefined,
        idNumber: '',
        phone: '',
        qq: '',
        wechat: '',
        email: '',
        campusId: undefined
      }
    },
    handleAvatarSuccess (res, file) {
      console.log(res.data)
      // this.teacherForm.picUrl = URL.createObjectURL(file.raw)
      this.teacherForm.picUrl = res.data
    },
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (file.type !== 'image/png' && file.type !== 'image/jpeg' && file.type !== 'image/jpg') {
        this.$message.error('上传头像图片只能是 JPG|JPEG|PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
    },
    submitTeacherInfo (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isCreateOrUpdateTeacher === 'create') {
            delete this.teacherForm.id
            people()._addOrUpdateTeacher({
              ...this.teacherForm
            }).then((res) => {
              if (res.status) {
                this.$message.success('教师信息新建成功')
                this.dialogAuthorizeTeacher = false
              } else {
                this.$message.error(res.message)
              }
            }).catch((err) => {
              this.$message.error(err)
            })
          } else if (this.isCreateOrUpdateTeacher === 'update') {
            delete this.teacherForm.birthDate
            delete this.teacherForm.organizationNames
            delete this.teacherForm.password
            delete this.teacherForm.roleNames
            delete this.teacherForm.shortPhone
            delete this.teacherForm.standbyPhone
            delete this.teacherForm.valid

            people()._addOrUpdateTeacher({
              ...this.teacherForm
            }).then((res) => {
              if (res.status) {
                this.$message.success('教师信息修改成功')
                this.dialogAuthorizeTeacher = false
              } else {
                this.$message.error(res.message)
              }
            }).catch((err) => {
              this.$message.error(err)
            })
          }
        } else {
          return false
        }
      })
    },
    addTeacherRuleArea (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isCreateOrUpdateTeacher === 'create') {
            delete this.teacherForm.id
            people()._addOrUpdateTeacher({
              ...this.teacherForm
            }).then((res) => {
              if (res.status) {
                this.dialogTeacherRuleArea = true
                this.dialogAuthorizeTeacher = false
                this.teacherInfo.id = res.data.id
                people()._getManagePersonDetail(this.teacherInfo.id).then((res) => {
                  if (res.status) {
                    this.teacherInfo = res.data
                  } else {
                    this.$message.error(res.message)
                  }
                }).catch((err) => {
                  this.$message.error(err)
                })
              } else {
                this.$message.error(res.message)
              }
            }).catch((err) => {
              this.$message.error(err)
            })
          } else if (this.isCreateOrUpdateTeacher === 'update') {
            delete this.teacherForm.birthDate
            delete this.teacherForm.organizationNames
            delete this.teacherForm.password
            delete this.teacherForm.roleNames
            delete this.teacherForm.shortPhone
            delete this.teacherForm.standbyPhone
            delete this.teacherForm.valid
            people()._addOrUpdateTeacher({
              ...this.teacherForm
            }).then((res) => {
              if (res.status) {
                this.dialogTeacherRuleArea = true
                this.dialogAuthorizeTeacher = false
                this.teacherInfo.id = res.data.id
                people()._getManagePersonDetail(this.teacherInfo.id).then((res) => {
                  if (res.status) {
                    this.teacherInfo = res.data
                  } else {
                    this.$message.error(res.message)
                  }
                }).catch((err) => {
                  this.$message.error(err)
                })
              } else {
                this.$message.error(res.message)
              }
            }).catch((err) => {
              this.$message.error(err)
            })
          }
        } else {
          return false
        }
      })
    },
    submitTeacherRuleArea () {
      people()._addManagerScope({
        managerId: this.teacherInfo.id,
        roleId: this.selectRoleId,
        scopeDetails: this.roleItems
      }).then((res) => {
        if (res.status) {
          this.$message.success('添加管辖权限成功')
          this.dialogTeacherRuleArea = false
          this.getManagePersonList()
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    updateManagePerson (item) {
      let studentRole = item.managerRoles.find((item) => {
        return item.name === '学生'
      })
      if (studentRole) {
        this.dialogAuthorizeStudent = true
        this.isCreateOrUpdateStudent = 'update'
        people()._getManagePersonDetail(item.id).then((res) => {
          if (res.status) {
            this.studentInfo = res.data
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error(err)
        })
      } else {
        this.dialogAuthorizeTeacher = true
        this.isCreateOrUpdateTeacher = 'update'
        people()._findTeacherBySn(item.sn).then((res) => {
          if (res.status) {
            this.teacherForm = res.data.userModel
            this.teacherForm.roleIds = res.data.roleModelList.map((item) => {
              return item.id
            })
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error(err)
        })
      }
    },
    clearStudentInfo () {
      this.studentInfo.id = undefined
      this.studentManage = ''
      this.selectRoleId = undefined
      this.roleItems = []
    },
    clearTeacherInfo () {
      this.selectRoleId = undefined
      this.roleItems = []
    },
    clearAuthorizeTeacher (formName) {
      this.$refs[formName].resetFields()
    }
  },
  filters: {
    rulefilter: function (item) {
      let str = (item.sn === null ? '' : (item.sn + ' ')) + (item.name === null ? '' : (item.name + ' ')) + (item.college === null ? '' : (item.college + ' ')) + (item.major === null ? '' : (item.major + ' ')) + (item.grade === null ? '' : (item.grade + ' ')) + (item.clazz === null ? '' : (item.clazz + ' '))
      return str
    },
    formatRole: function (item) {
      if (item.managerRoles) {
        return item.managerRoles.reduce((accumulator, currentValue) => {
          let name = currentValue.name
          let status = currentValue.valid === 1 ? '（正常）' : '（冻结）'
          return accumulator + '' + name + status
        }, '')
      } else {
        return '无'
      }
    }
  }
}
</script>
<style  lang="less"  scoped>
.el-dialog__body {
  text-align: center;
}
.file-uploader i {
  color: gray;
  font-size: 15px;
  margin-right: 5px;
  vertical-align: middle;
}
.file-uploader .download-template {
  margin: 15px;
  color: #3a8ee6;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  margin-right: 10px;
  color: #8c939d;
  width: 100px;
  height: 136px;
  line-height: 136px;
  text-align: center;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar {
  width: 100px;
  height: 136px;
  display: block;
}
.el-radio + .el-radio {
  margin-left: 15px;
}
</style>
